package cn.itsource.service;

import cn.hutool.http.HttpUtil;
import cn.itsource.config.WxPlusProperties;
import cn.itsource.constants.Constants;
import cn.itsource.pojo.dto.AccessTokenDto;
import cn.itsource.pojo.dto.PhoneInfo;
import cn.itsource.pojo.dto.RegisterDto;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class WxService {

    private WxPlusProperties wxPlusProperties;

    public RegisterDto getOpenId(String code){
        String sendUrl = String.format(
                Constants.Driver.Register_Url,
                wxPlusProperties.getAppId(),
                wxPlusProperties.getAppSecret(),code);
        String data = HttpUtil.get(sendUrl);
        RegisterDto registerDto = JSONObject.parseObject(data,RegisterDto.class);
        return registerDto;
    }
    public String getPhone(String phoneCode){
        //获取access_token
        String sendAccess = String.format(Constants.Driver.USER_GET_ACCESS_TOKEN, wxPlusProperties.getAppId(), wxPlusProperties.getAppSecret());
        String accessData = HttpUtil.get(sendAccess);
        AccessTokenDto accessTokenDto = JSONObject.parseObject(accessData, AccessTokenDto.class);
        String accessToken = accessTokenDto.getAccessToken();
        //获取手机号
        String sendPhone = String.format(Constants.Driver.USER_GET_PHONE_NUMBER, accessToken);
        HashMap<String, Object> map = new HashMap<>();
        map.put(Constants.Driver.CODE,phoneCode);
        String post = HttpUtil.post(sendPhone, map);
        PhoneInfo phoneInfo = JSONObject.parseObject(post, PhoneInfo.class);
        String phoneNumber = phoneInfo.getPhone_info().getPhoneNumber();
        return phoneNumber;
    }
}
